<script setup>
import { ref, watch } from 'vue'
import { studentOptions } from '../../services/student'

const props = defineProps({
  editMode: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['confirm', 'closed'])

// 表单数据
const form = ref({
  id: '',
  account: '',
  name: '',
  phone: '',
  school: '',
  class: '',
  group: '',
  teacher: '',
  points: 0,
  expireTime: ''
})

// 表单校验规则
const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 选项
const schoolOptions = studentOptions.schools
const classOptions = studentOptions.classes
const groupOptions = studentOptions.groups
const teacherOptions = studentOptions.teachers

// 对话框可见性
const dialogVisible = ref(false)
const formRef = ref(null)

// 监听编辑数据变化
watch(() => props.editData, (newVal) => {
  if (newVal) {
    // 克隆对象以避免直接修改props
    form.value = { ...newVal }
  }
}, { immediate: true, deep: true })

// 打开对话框
const openDialog = () => {
  dialogVisible.value = true
  
  // 如果不是编辑模式，重置表单
  if (!props.editMode) {
    resetForm()
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    id: '',
    account: '',
    name: '',
    phone: '',
    school: '',
    class: '',
    group: '',
    teacher: '',
    points: 0,
    expireTime: ''
  }
  
  // 如果表单已挂载，使用element-plus的重置方法
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 确认提交
const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    emit('confirm', { ...form.value })
    dialogVisible.value = false
  } catch (error) {
    // 表单验证失败
    console.error('表单验证失败:', error)
  }
}

// 对话框关闭处理
const handleClosed = () => {
  emit('closed')
}

// 对外暴露方法
defineExpose({
  openDialog
})
</script>

<template>
  <el-dialog
    :title="editMode ? '编辑学生' : '添加学生'"
    v-model="dialogVisible"
    width="500px"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      class="student-form"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" :disabled="editMode" />
      </el-form-item>
      
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>
      
      <el-form-item label="学校">
        <el-select v-model="form.school" placeholder="请选择学校" clearable filterable allow-create>
          <el-option
            v-for="item in schoolOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="班级">
        <el-select v-model="form.class" placeholder="请选择班级" clearable filterable allow-create>
          <el-option
            v-for="item in classOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="小组">
        <el-select v-model="form.group" placeholder="请选择小组" clearable filterable allow-create>
          <el-option
            v-for="item in groupOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="老师">
        <el-select v-model="form.teacher" placeholder="请选择老师" clearable filterable allow-create>
          <el-option
            v-for="item in teacherOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="积分">
        <el-input-number v-model="form.points" :min="0" :max="9999" />
      </el-form-item>
      
      <el-form-item label="到期时间">
        <el-date-picker
          v-model="form.expireTime"
          type="date"
          placeholder="选择到期日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.student-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.student-form :deep(.el-select),
.student-form :deep(.el-date-editor) {
  width: 100%;
}

:deep(.el-input__wrapper),
:deep(.el-select .el-input__wrapper),
:deep(.el-date-editor.el-input__wrapper) {
  background-color: var(--el-bg-color);
  box-shadow: 0 0 0 1px var(--el-border-color) inset;
}

:deep(.el-form-item__label) {
  color: var(--el-text-color-regular);
}

:deep(.el-input-number__decrease),
:deep(.el-input-number__increase) {
  background-color: var(--el-fill-color-light);
  border-color: var(--el-border-color);
  color: var(--el-text-color-regular);
}

:deep(.el-date-editor .el-range-separator) {
  color: var(--el-text-color-secondary);
}
</style>
